package com.mobiusws.reports.action;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.mobiusws.reports.dao.DailyFraudDetailDao;
import com.mobiusws.reports.dao.DailyFraudSummaryDao;
import com.mobiusws.reports.dao.TestDao;
import com.mobiusws.reports.dao.QueryDetailDao;
import com.mobiusws.reports.model.CallsNodup;
import com.mobiusws.reports.model.DailyFraudDetail;
import com.mobiusws.reports.model.DailyFraudSummary;
import com.mobiusws.reports.model.LoginInfo;
import com.mobiusws.util.DateUtil;
import com.mobiusws.util.JsonUtil;
import com.mobiusws.util.MaskUtil;
import com.mobiusws.util.MessageUtil;
import com.mobiusws.util.OperatorConstants;
import com.mobiusws.util.ExportManage;
import com.mobiusws.util.ExportReport;
import com.mobiusws.util.StringUtils;
import com.opensymphony.xwork2.ActionSupport;

public class QueryDetailAction extends ActionSupport {

	private static final long serialVersionUID = 5395964004991248282L;

	@Resource
	private QueryDetailDao queryDetailDao;
	@Resource
	private JsonUtil jsonUtil;
	@Resource
	private MessageUtil messageUtil;

	private String result;

	private String selDate;
	private int start;
	private int limit;
	private int total;

	private String trafficTime;
	private String startDate;
	private String endDate;
	private String smsisdn;
	private String imsi;
	private int queryHourFlag;
	private int queryType;
	private String queryTypeName;

	private String fileName;
	private String bQuery;
	private String suffix;

	public String getQueryTypeName() {
		return queryTypeName;
	}

	public void setQueryTypeName(String queryTypeName) {
		this.queryTypeName = queryTypeName;
	}

	public String getSuffix() {
		return suffix;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getBQuery() {
		return bQuery;
	}

	public void setBQuery(String bQuery) {
		this.bQuery = bQuery;
	}

	public String getSelDate() {
		return selDate;
	}

	public void setSelDate(String selDate) {
		this.selDate = selDate;
	}

	public String getTrafficTime() {
		return trafficTime;
	}

	public void setTrafficTime(String trafficTime) {
		this.trafficTime = trafficTime;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	// a getter is required to get the result in pages
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public int getQueryType() {
		return queryType;
	}

	public void setQueryType(int queryType) {
		this.queryType = queryType;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getSmsisdn() {
		return smsisdn;
	}

	public void setSmsisdn(String smsisdn) {
		this.smsisdn = smsisdn;
	}

	public int getQueryHourFlag() {
		return queryHourFlag;
	}

	public void setQueryHourFlag(int queryHourFlag) {
		this.queryHourFlag = queryHourFlag;
	}

	public String getImsi() {
		return imsi;
	}

	public void setImsi(String imsi) {
		this.imsi = imsi;
	}

	public void updateSmsisdn(String smsisdn) {
		if (smsisdn == null || smsisdn == "") {
			smsisdn = "";
		}

		if (queryType != 4) {
			smsisdn = StringUtils.matchString(smsisdn);
		}
		setImsi(smsisdn);
		if (queryType == 1) {
			if (!smsisdn.equals("")) {
				String[] tmp = smsisdn.split(",");
				String t_msisdn = "";
				for (int i = 0; i < tmp.length; i++) {
					t_msisdn += ","
							+ String.valueOf(MaskUtil.intXORMask(Long
									.parseLong(tmp[i])));
				}
				if (!t_msisdn.equals("") && t_msisdn.startsWith(",")) {
					if (!t_msisdn.equals("") && !t_msisdn.equals("0"))
						this.smsisdn = t_msisdn.replaceFirst(",", "");
				} else {
					this.smsisdn = t_msisdn;
				}
			}
		} else if (queryType == 2) {
			if (!smsisdn.equals("")) {
				String[] tmp = smsisdn.split(",");
				String t_msisdn = "";
				for (int i = 0; i < tmp.length; i++) {
					String tmpResult = queryDetailDao.getSmsisdnByImsi(this,
							tmp[i]);
					if (!tmpResult.equals("") && !tmpResult.equals("0"))
						t_msisdn += "," + tmpResult;
				}
				if (!t_msisdn.equals("") && t_msisdn.startsWith(",")) {
					this.smsisdn = t_msisdn.replaceFirst(",", "");
				} else {
					this.smsisdn = t_msisdn;
					// System.out.println("smsisdn="+this.smsisdn);
				}
			}
		} else if (queryType == 3) {
			this.smsisdn = String.valueOf(MaskUtil.intXORMask(Long
					.parseLong(smsisdn)));
		} else if (queryType == 4) {
			this.smsisdn = smsisdn;
			if (smsisdn.indexOf("_") > 0)
				setImsi(smsisdn.substring(0, smsisdn.indexOf("_")));
		}
	}

	public String beforeExecute() throws Exception {
		Date trafficDate;
		if (trafficTime.length() == 10) {
			trafficDate = DateUtil.string2Date("yyyy-MM-dd", trafficTime);
		} else if (trafficTime.length() == 13) {
			trafficDate = DateUtil.string2Date("yyyy-MM-dd HH", trafficTime);
		} else {
			trafficDate = null;
		}

		if(this.queryType==1) {
			trafficDate = DateUtil.getNext1Hour(trafficDate);
			startDate = DateUtil.date2String("yyyy-MM-dd HH",
					DateUtil.getPrev24Hour(trafficDate));
			endDate = DateUtil.date2String("yyyy-MM-dd HH", trafficDate);
		} else if(this.queryType==4) {
			startDate = DateUtil.date2String("yyyy-MM-dd HH", trafficDate);
			endDate = DateUtil.date2String("yyyy-MM-dd HH", DateUtil.getAfterDate(trafficDate, 1));
		}
		updateSmsisdn(this.smsisdn);
		return "page";
	}

	@Override
	public String execute() throws Exception {
		// Thread.sleep(1000);
		// System.out.printf("selDate=%s, start=%s, limit=%s\n",
		// this.getSelDate(), this.getStart(), this.getLimit());
		if (getQueryHourFlag() == 1) {
			this.setStartDate(DateUtil.GMTCovert(
					OperatorConstants.TIMEZONE,
					"GMT+0:00",
					DateUtil.date2String("yyyy-MM-dd HH:mm:ss",
							DateUtil.string2Date("yyyy-MM-dd HH", startDate))));
		} else if (getQueryHourFlag() == 0) {
			this.setStartDate(DateUtil.GMTCovert(
					OperatorConstants.TIMEZONE,
					"GMT+0:00",
					DateUtil.date2String("yyyy-MM-dd HH:mm:ss",
							DateUtil.string2Date("yyyy-MM-dd", startDate))));
		}

		if (getQueryHourFlag() == 1) {
			this.setEndDate(DateUtil.GMTCovert(
					OperatorConstants.TIMEZONE,
					"GMT+0:00",
					DateUtil.date2String("yyyy-MM-dd HH:mm:ss",
							DateUtil.string2Date("yyyy-MM-dd HH", getEndDate()))));
		} else if (getQueryHourFlag() == 0) {
			this.setEndDate(DateUtil.GMTCovert(OperatorConstants.TIMEZONE,
					"GMT+0:00", DateUtil.getNextDay(DateUtil.string2Date(
							"yyyy-MM-dd", getEndDate()))));
		}

		List<CallsNodup> list = null;
		if (this.queryType == 1) {
			list = queryDetailDao.getQuerySubDetail(this);
		} else if (this.queryType == 4) {
			list = queryDetailDao.getDroppedDetail(this);
		}
		this.result = jsonUtil.getJsonByList(list, this.getTotal(), true);
		// System.out.println(this.result);
		ServletActionContext.getResponse().setContentType(
				"text/plain;charset=utf-8");
		PrintWriter out = ServletActionContext.getResponse().getWriter();
		out.print(this.result);
		out.flush();
		out.close();
		return SUCCESS;
	}

	public String export() throws Exception {
		if (isMaxExceeded(total)) {
			this.bQuery = "E";
		} else {
			this.bQuery = "C";
			this.fileName = createExportFiles() + "." + this.suffix;
		}
		return "export";
	}

	private boolean isMaxExceeded(int total) {
		String maxSizeStr = messageUtil.getString("max.out.size");
		int maxSize = Integer.parseInt(maxSizeStr);
		return total > maxSize;
	}

	private String createExportFiles() {
		ExportManage exportManage = new ExportManage();
		ExportReport reportStruct = new ExportReport();

		String[] reportTitleArray = { "s_msisdn", "o_msisdn", "imsi", "imei",
				"vendor", "model", "call_type", "call_type_name", "call_time",
				"cell_id", "duration", "trunk_in", "trunk_out" };
		String reportTitle = "s_msisdn,o_msisdn,imsi,imei,vendor,model,call_type,call_type_name,call_time,cell_id,duration,trunk_in,trunk_out";

		reportStruct.setReportName("root");
		reportStruct.setReportDate(DateUtil.date2String("yyyyMMddHHmmss",
				new Date()));

		reportStruct.setReportTitle(reportTitle);
		reportStruct.setReportTitleArray(reportTitleArray);
		reportStruct.setTableColumnsArray(reportTitleArray);
		String queryCriteria = String.format("msisdn: %s, daterange: %s~%s",
				getSmsisdn(), getStartDate(), getEndDate());
		reportStruct.setQueryCriteria(queryCriteria);
		// reportStruct.setTableName("daily_fraud_detail_report");

		long maskBits = OperatorConstants.MASK_VALUE;
		String outputPath = "/opt/GK2/portal/querydata";
		exportManage.DBQueryReportDaily(OperatorConstants.MCC + "_"
				+ OperatorConstants.MNC, "0", maskBits, reportStruct,
				outputPath,
				queryDetailDao.getQuerySubDetailExport(getQueryType()));

		return reportStruct.getReportName() + "_"
				+ reportStruct.getReportDate();
	}

}
